package com.hh.releasenode.shiro;

import com.alibaba.fastjson.JSONObject;
import com.hh.releasenode.utils.HttpContextUtils;
import com.hh.releasenode.utils.Response;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName OAuth2Filter
 * @Description token 方式过滤器
 * @Author KunxianLi
 * Date 2020/6/28 10:48
 * Version 1.0
 **/
public class OAuth2Filter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String requestToken = getRequestToken((HttpServletRequest) request);

        if(StringUtils.isBlank(requestToken)){
            return null;
        }

        return new OAuth2Token(requestToken);
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        String requestToken = getRequestToken((HttpServletRequest) request);

        if(StringUtils.isBlank(requestToken)){
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
            Response invalid_toekn = Response.error("invalid toekn");
            httpResponse.getWriter().print(JSONObject.toJSONString(invalid_toekn));
        }
        //登陆验证，最终会执行ShiroRealm中的登陆验证方法
        return executeLogin(request,response);
    }

    /*
     * @Author KunxianLi
     * @Description 从请求中获取token
     * @Date 2020/6/28 10:53
     * @Param [request]
     * @return java.lang.String
     **/
    private String getRequestToken(HttpServletRequest request){
        String token = request.getHeader("token");

        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }

        return token;
    }
}
